#include "dri_usart.h"
#include "dri_systick.h"
#include "dri_servo.h"
#include <string.h>

volatile DogState dog_state = A;

// USART6 的变量
char usart6_rx_buffer[20];
int usart6_rx_index = 0;

// USART2 的变量
char usart2_rx_buffer[20];
int usart2_rx_index = 0;

// USART3 的变量 (用于WiFi控制)
char usart3_rx_buffer[100];
int usart3_rx_index = 0;
volatile uint8_t usart3_cmd_ready = 0;

// USART6 初始化
void dri_usart6_init(void)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    USART_InitTypeDef  USART_InitStruct;
    NVIC_InitTypeDef   NVIC_InitStruct;
    
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE);

    GPIO_PinAFConfig(GPIOG, GPIO_PinSource9, GPIO_AF_USART6);
    GPIO_PinAFConfig(GPIOG, GPIO_PinSource14, GPIO_AF_USART6);
    
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_14;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOG, &GPIO_InitStruct);
    
    USART_InitStruct.USART_BaudRate = 115200;
    USART_InitStruct.USART_WordLength = USART_WordLength_8b;
    USART_InitStruct.USART_StopBits = USART_StopBits_1;
    USART_InitStruct.USART_Parity = USART_Parity_No;
    USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_Init(USART6, &USART_InitStruct);

    USART_ITConfig(USART6, USART_IT_RXNE, ENABLE);
    NVIC_InitStruct.NVIC_IRQChannel = USART6_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
    USART_ClearFlag(USART6, USART_FLAG_TC);
    USART_Cmd(USART6, ENABLE);
    
    // 初始化接收缓冲区
    memset(usart6_rx_buffer, 0, sizeof(usart6_rx_buffer));
    usart6_rx_index = 0;
}

// USART2 初始化
void dri_usart2_init(void)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    USART_InitTypeDef  USART_InitStruct;
    NVIC_InitTypeDef   NVIC_InitStruct;
    
    // 使能 GPIOA 和 USART2 时钟
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

    // 配置 PA2 和 PA3 为 USART2 功能
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
    
    // 初始化 GPIO
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;  // PA2(TX), PA3(RX)
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOA, &GPIO_InitStruct);
    
    // 配置 USART2
    USART_InitStruct.USART_BaudRate = 115200;
    USART_InitStruct.USART_WordLength = USART_WordLength_8b;
    USART_InitStruct.USART_StopBits = USART_StopBits_1;
    USART_InitStruct.USART_Parity = USART_Parity_No;
    USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_Init(USART2, &USART_InitStruct);

    // 使能接收中断
    USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
    
    // 配置 NVIC：设置最高抢占优先级
    NVIC_InitStruct.NVIC_IRQChannel = USART2_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;  // 最高抢占优先级
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;         // 子优先级最高
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
    
    // 清除标志位并使能 USART2
    USART_ClearFlag(USART2, USART_FLAG_TC);
    USART_Cmd(USART2, ENABLE);
    
    // 初始化接收缓冲区
    memset(usart2_rx_buffer, 0, sizeof(usart2_rx_buffer));
    usart2_rx_index = 0;
}

// USART3 初始化 (用于WiFi控制)
void dri_usart3_init(void)
{
    GPIO_InitTypeDef   GPIO_InitStruct;
    USART_InitTypeDef  USART_InitStruct;
    NVIC_InitTypeDef   NVIC_InitStruct;
    
    // 使能 GPIOB 和 USART3 时钟
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

    // 配置 PB10 和 PB11 为 USART3 功能
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_USART3);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_USART3);
    
    // 初始化 GPIO
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;  // PB10(TX), PB11(RX)
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOB, &GPIO_InitStruct);
    
    // 配置 USART3
    USART_InitStruct.USART_BaudRate = 115200;  // ESP8266默认波特率
    USART_InitStruct.USART_WordLength = USART_WordLength_8b;
    USART_InitStruct.USART_StopBits = USART_StopBits_1;
    USART_InitStruct.USART_Parity = USART_Parity_No;
    USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_Init(USART3, &USART_InitStruct);

    // 使能接收中断
    USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
    
    // 配置 NVIC
    NVIC_InitStruct.NVIC_IRQChannel = USART3_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;  // 优先级设置
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
    
    // 清除标志位并使能 USART3
    USART_ClearFlag(USART3, USART_FLAG_TC);
    USART_Cmd(USART3, ENABLE);
    
    // 初始化接收缓冲区
    memset(usart3_rx_buffer, 0, sizeof(usart3_rx_buffer));
    usart3_rx_index = 0;
    usart3_cmd_ready = 0;
    
    printf("USART3 Initialized for WiFi control\r\n");
}

// USART3 发送字符串
void usart3_send_string(const char *str)
{
    while(*str)
    {
        USART_SendData(USART3, *str);
        while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
        USART_ClearFlag(USART3, USART_FLAG_TC);
        str++;
    }
}



// 标准输出函数 (使用USART6)
int fputc(int ch, FILE *f)
{
    USART_SendData(USART6, ch);
    while(USART_GetFlagStatus(USART6, USART_FLAG_TC) == RESET);
    USART_ClearFlag(USART6, USART_FLAG_TC);
    return ch;
}



// USART6 中断处理程序
void USART6_IRQHandler(void)
{
    char received_char = 0;
    if(USART_GetITStatus(USART6, USART_IT_RXNE))
    {    
        // 清除中断标志位
        USART_ClearITPendingBit(USART6, USART_IT_RXNE);
        
        // 读取接收到的字符
        received_char = USART_ReceiveData(USART6);
        
        // 回传接收到的字符
        USART_SendData(USART6, received_char);
        while(USART_GetFlagStatus(USART6, USART_FLAG_TC) == RESET);
        USART_ClearFlag(USART6, USART_FLAG_TC);
        
        // 处理接收到的字符
        if(usart6_rx_index < (sizeof(usart6_rx_buffer) - 1))
        {
            // 如果收到回车或换行符，处理命令
            if(received_char == '\r' || received_char == '\n')
            {
                usart6_rx_buffer[usart6_rx_index] = '\0'; // 确保字符串以null结尾
                
                // 处理命令
                if(strcmp(usart6_rx_buffer, "led_close") == 0)
                {
                    GPIO_SetBits(GPIOF, GPIO_Pin_8);
                }
                else if(strcmp(usart6_rx_buffer, "led_open") == 0)
                {
                    GPIO_ResetBits(GPIOF, GPIO_Pin_8);
                }
                else if(strcmp(usart6_rx_buffer, "fan_open") == 0)
                {
                    GPIO_SetBits(GPIOC, GPIO_Pin_6);
                }
                else if(strcmp(usart6_rx_buffer, "fan_close") == 0)
                {
                    GPIO_ResetBits(GPIOC, GPIO_Pin_6);
                }
                else if(strcmp(usart6_rx_buffer, "beep_open") == 0)  
                {
                    GPIOA->ODR |= 0x01<<15;				
                }
                else if(strcmp(usart6_rx_buffer, "beep_close") == 0)
                {
                    GPIOA->ODR &=~(0x01<<15);
                }
                else if(strcmp(usart6_rx_buffer, "forward") == 0)//前进
                {                                                 
                    dog_state = B;                      
                }
                else if(strcmp(usart6_rx_buffer, "stand") == 0)//起立
                {
                    dog_state = D;
                }
                else if(strcmp(usart6_rx_buffer, "sit") == 0)//坐下
                {
                    dog_state = E;
                }
                else if(strcmp(usart6_rx_buffer, "lie") == 0)//卧下
                {
                    dog_state = F;
                }
                else if(strcmp(usart6_rx_buffer, "backward") == 0)//后退
                {                                    
                    dog_state = C;
                }
                else if(strcmp(usart6_rx_buffer, "oled") == 0)//后退
            {                                    
                dog_state = G;
            }
                // 重置接收缓冲区和索引
                memset(usart6_rx_buffer, 0, sizeof(usart6_rx_buffer));
                usart6_rx_index = 0;
            }
            else
            {
                // 存储接收到的字符
                usart6_rx_buffer[usart6_rx_index++] = received_char;
            }
        }
        else
        {
            // 缓冲区已满，重置
            memset(usart6_rx_buffer, 0, sizeof(usart6_rx_buffer));
            usart6_rx_index = 0;
        }
    }
}

// USART2 中断处理程序
void USART2_IRQHandler(void)
{
    char received_char = 0;
    if(USART_GetITStatus(USART2, USART_IT_RXNE))
    {    
        // 清除中断标志位
        USART_ClearITPendingBit(USART2, USART_IT_RXNE);
        
        // 读取接收到的字符
        received_char = USART_ReceiveData(USART2);
        
        // 将接收到的字符转发到USART6（串口调试工具）
        USART_SendData(USART6, received_char);
        while(USART_GetFlagStatus(USART6, USART_FLAG_TC) == RESET);
        USART_ClearFlag(USART6, USART_FLAG_TC);
        
        // 处理接收到的字符
        if(usart2_rx_index < (sizeof(usart2_rx_buffer) - 1))
        {
            // 如果收到回车或换行符，处理命令
            if(received_char == '\r' || received_char == '\n')
            {
                usart2_rx_buffer[usart2_rx_index] = '\0'; // 确保字符串以null结尾
                
                // 处理命令
                if(strcmp(usart2_rx_buffer, "led_close") == 0)
                {
                    GPIO_SetBits(GPIOF, GPIO_Pin_8);
                }
                else if(strcmp(usart2_rx_buffer, "led_open") == 0)
                {
                    GPIO_ResetBits(GPIOF, GPIO_Pin_8);
                }
                else if(strcmp(usart2_rx_buffer, "fan_open") == 0)
                {
                    GPIO_SetBits(GPIOC, GPIO_Pin_6);
                }
                else if(strcmp(usart2_rx_buffer, "fan_close") == 0)
                {
                    GPIO_ResetBits(GPIOC, GPIO_Pin_6);
                }
                else if(strcmp(usart2_rx_buffer, "beep_open") == 0)
                {
                    GPIOA->ODR |= 0x01<<15;
                }
                else if(strcmp(usart2_rx_buffer, "beep_close") == 0)
                {
                    GPIOA->ODR &=~(0x01<<15);
                }
                else if(strcmp(usart2_rx_buffer, "forward") == 0)//前进
                {                                                 
                    dog_state = B;                      
                }
                else if(strcmp(usart2_rx_buffer, "stand") == 0)//起立
                {
                    dog_state = D;
                }
                else if(strcmp(usart2_rx_buffer, "sit") == 0)//坐下
                {
                    dog_state = E;
                }
                else if(strcmp(usart2_rx_buffer, "lie") == 0)//卧下
                {
                    dog_state = F;
                }
                else if(strcmp(usart2_rx_buffer, "backward") == 0)//后退
                {                                    
                    dog_state = C;
                }
                else if(strcmp(usart2_rx_buffer, "oled") == 0)//后退
            {                                    
                dog_state = G;
            }
                // 重置接收缓冲区和索引
                memset(usart2_rx_buffer, 0, sizeof(usart2_rx_buffer));
                usart2_rx_index = 0;
            }
            else
            {
                // 存储接收到的字符
                usart2_rx_buffer[usart2_rx_index++] = received_char;
            }
        }
        else
        {
            // 缓冲区已满，重置
            memset(usart2_rx_buffer, 0, sizeof(usart2_rx_buffer));
            usart2_rx_index = 0;
        }
    }
}

// USART3 中断处理程序
// USART3 中断处理程序
void USART3_IRQHandler(void)
{
    char received_char = 0;
    if(USART_GetITStatus(USART3, USART_IT_RXNE))
    {    
        // 清除中断标志位
        USART_ClearITPendingBit(USART3, USART_IT_RXNE);
        
        // 读取接收到的字符
        received_char = USART_ReceiveData(USART3);
        
        // 将接收到的字符转发到USART6
        USART_SendData(USART6, received_char);
        while(USART_GetFlagStatus(USART6, USART_FLAG_TC) == RESET);
        USART_ClearFlag(USART6, USART_FLAG_TC);
        
        // 处理接收到的字符
        if(received_char == '\r' || received_char == '\n')
        {
            usart3_rx_buffer[usart3_rx_index] = '\0'; // 确保字符串以null结尾
            
            // 处理命令
            if(strcmp(usart3_rx_buffer, "led_close") == 0)
            {
                GPIO_SetBits(GPIOF, GPIO_Pin_8);
            }
            else if(strcmp(usart3_rx_buffer, "led_open") == 0)
            {
                GPIO_ResetBits(GPIOF, GPIO_Pin_8);
            }
            else if(strcmp(usart3_rx_buffer, "fan_open") == 0)
            {
                GPIO_SetBits(GPIOC, GPIO_Pin_6);
            }
            else if(strcmp(usart3_rx_buffer, "fan_close") == 0)
            {
                GPIO_ResetBits(GPIOC, GPIO_Pin_6);
            }
            else if(strcmp(usart3_rx_buffer, "beep_open") == 0)
            {
                GPIOA->ODR |= 0x01<<15;
            }
            else if(strcmp(usart3_rx_buffer, "beep_close") == 0)
            {
                GPIOA->ODR &=~(0x01<<15);
            }
            else if(strcmp(usart3_rx_buffer, "forward") == 0)//前进
            {                                                 
                dog_state = B;                      
            }
            else if(strcmp(usart3_rx_buffer, "stand") == 0)//起立
            {
                dog_state = D;
            }
            else if(strcmp(usart3_rx_buffer, "sit") == 0)//坐下
            {
                dog_state = E;
            }
            else if(strcmp(usart3_rx_buffer, "lie") == 0)//卧下
            {
                dog_state = F;
            }
            else if(strcmp(usart3_rx_buffer, "backward") == 0)//后退
            {                                    
                dog_state = C;
            }
			else if(strcmp(usart3_rx_buffer, "oled") == 0)//后退
            {                                    
                dog_state = G;
            }
            
            // 重置接收缓冲区和索引
            memset(usart3_rx_buffer, 0, sizeof(usart3_rx_buffer));
            usart3_rx_index = 0;
        }
        else
        {
            // 存储接收到的字符
            if(usart3_rx_index < (sizeof(usart3_rx_buffer) - 1))
            {
                usart3_rx_buffer[usart3_rx_index++] = received_char;
            }
            else
            {
                // 缓冲区已满，重置
                memset(usart3_rx_buffer, 0, sizeof(usart3_rx_buffer));
                usart3_rx_index = 0;
            }
        }
    }
}
